package com.gdpu.pbss.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdpu.pbss.Constants.Constants;
import com.gdpu.pbss.DTO.ManagerDTO;
import com.gdpu.pbss.exception.ServiceException;
import com.gdpu.pbss.mapper.ManagerMapper;
import com.gdpu.pbss.pojo.Manager;
import com.gdpu.pbss.service.ManagerService;
import com.gdpu.pbss.utils.TokenUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ManagerServiceImpl extends ServiceImpl<ManagerMapper, Manager> implements ManagerService {



    @Override
    public ManagerDTO login(ManagerDTO managerdto) {
        Manager one = getManager(managerdto);

        if(one!=null){
            BeanUtils.copyProperties(one,managerdto);


            //设置token
            String token= TokenUtils.getManagerToken(managerdto.getManageId(),managerdto.getManagePassword());
            managerdto.setToken(token);
            return managerdto;
        }else {
            throw new ServiceException(Constants.CODE_400,"用户名或密码错误");
        }

    }

    @Override
    public Manager register(ManagerDTO managerdto) {
        Manager one = getManager(managerdto);
        if (one==null){
           one=new Manager();
             one.setManageName(managerdto.getManageName());
             one.setManagePassword(managerdto.getManagePassword());
            save(one);

        }else {
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }

        return one;
    }

    public Manager getManager(ManagerDTO managerdto){
        QueryWrapper<Manager> qw=new QueryWrapper<>();
        qw.eq("manage_name",managerdto.getManageName());
        qw.eq("manage_password",managerdto.getManagePassword());
        Manager one;
        try {
            one = getOne(qw);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return one;
    }
}
